<template>
  <div class="all-content">
    <BreadList :breadList="breadList"></BreadList>
    <div class="manage-content"
      v-loading="listLoading"
      element-loading-text="加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.5)">
      <div class="search-content">
        <el-button v-if="buttonList.some(item => item.value === '/ManageList/add')" type="primary" @click="addTask">新建任务</el-button>
      </div>
      <div class="table-content">
        <div class="list" v-show="tableData.length > 0">
          <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%;height: 100%"
            height="100%">
            <el-table-column
              label="序号"
              type="index"
              width="68">
              <template slot-scope="scope">
                <span>{{(tablePageData.currentPage - 1) * tablePageData.pageSize + scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="任务名称"
              min-width="150">
              <template slot-scope="scope">
                <!-- <el-tooltip :content="scope.row.taskName" placement="top"> -->
                  <span class="desc-style">{{scope.row.taskName}}</span>
                <!-- </el-tooltip> -->
              </template>
            </el-table-column>
            <el-table-column
              prop="type"
              :formatter="taskTypeFormat"
              label="任务分类"
              width="110">
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="200">
            </el-table-column>
            <el-table-column
              prop="lastExcuteTime"
              label="上次运行时间"
              width="200">
            </el-table-column>
            <el-table-column
              prop="nextExcuteTime"
              label="下次运行时间"
              width="200">
            </el-table-column>
            <el-table-column
              prop="taskStatus"
              :formatter="taskStatusFormat"
              label="任务状态"
              width="110">
            </el-table-column>
            <el-table-column
              prop="name"
              label="创建用户"
              min-width="150">
              <template slot-scope="scope">
                <!-- <el-tooltip :content="scope.row.createLoginName" placement="top"> -->
                  <span class="desc-style">{{scope.row.createLoginName}}</span>
                <!-- </el-tooltip> -->
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="257">
              <template slot-scope="scope">
                <span v-if="buttonList.some(item => item.value === '/ManageList/view')" class="operate-item" @click="itemLook(scope.row)"><span class="icon icon-look"></span>查看</span>
                <span v-if="scope.row.canUpdate && buttonList.some(item => item.value === '/ManageList/edit')" :class="['operate-item', {'disabled': !scope.row.canUpdate}]" @click="itemEdit(scope.row)"><span class="icon icon-edit"></span>编辑</span>
                <span v-if="scope.row.canDelete && buttonList.some(item => item.value === '/ManageList/delete')" :class="['operate-item delete', {'disabled': !scope.row.canDelete}]" @click="itemDelete(scope.row)"><span class="icon icon-delete"></span>删除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page-box" v-show="tableData.length > 0">
          <el-pagination
            class="table-page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="tablePageData.currentPage"
            :page-sizes="tablePageData.pageSizes"
            :page-size="tablePageData.pageSize"
            background
            layout="total, sizes, slot, prev, pager, next"
            :total="tablePageData.total">
            <span class="page-item first" @click="handleCurrentChange(1)">首页</span>
          </el-pagination>
          <el-pagination
            class="table-page"
            @current-change="handleCurrentChange"
            :current-page="tablePageData.currentPage"
            :page-sizes="tablePageData.pageSizes"
            :page-size="tablePageData.pageSize"
            background
            layout="slot"
            :total="tablePageData.total">
            <span class="page-item" @click="handleCurrentChange(Math.ceil(tablePageData.total/tablePageData.pageSize))">末页</span>
            <span class="page-jumper">跳至<el-input class="page-num" v-model="tablePageData.inputNum" @input.native="tablePageData.inputNum = JSON.stringify(tablePageData.inputNum).replace(/[^0-9]/g,'')" @blur="handleCurrentChange(tablePageData.inputNum)" @keyup.enter.native="handleCurrentChange(tablePageData.inputNum)"></el-input>页</span>
          </el-pagination>
        </div>
        <Empty v-show="tableData.length === 0" imgHeight="42%" />
      </div>
      <el-dialog
        :title="taskDialogTitle"
        v-if="taskModelShow"
        :visible.sync="taskModelShow"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :append-to-body="false"
        width="876px"
        custom-class="detail-dialog"
        >
          <div class="task-content">
            <div class="task-item">
              <span class="item-label">任务名称</span>
              <!-- :class="['item-value', {'red': required && !taskInfoList.taskName}]" -->
              <el-input 
                class="item-value"
                v-model="taskInfoList.taskName" 
                placeholder="请输入任务名称"
                clearable
                maxlength="50"></el-input>
            </div>
            <div class="task-item">
              <span class="item-label">模型</span>
              <el-select 
                :class="['item-value', {'red': required && !taskInfoList.modelId}]"
                v-model="taskInfoList.modelId"
                placeholder="请选择模型"
                @change="modelChange"
                :disabled="taskDialogTitle === '编辑任务'">
                <el-option
                  v-for="item in modelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <!-- <el-cascader
                :class="['item-value', {'red': required && !taskInfoList.modelId}]"
                v-model="taskInfoList.modelId"
                :options="modelList"
                :show-all-levels="false"
                :emitPath="false"
                :props="modelListProps"
                @change="modelChange"
                placeholder="请选择模型"></el-cascader> -->
            </div>
            <div class="task-item">
              <span class="item-label">数据集</span>
              <el-select 
                :class="['item-value', {'red': required && !taskInfoList.dataSet}]"
                v-model="taskInfoList.dataSet"
                placeholder="请选择数据集"
                :disabled="taskDialogTitle === '编辑任务'">
                <el-option
                  v-for="item in dataSetList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="task-item">
              <span class="item-label">任务类型</span>
              <el-select 
                :class="['item-value', {'red': required && !taskInfoList.taskType}]"
                v-model="taskInfoList.taskType"
                placeholder="请选择任务类型">
                <el-option
                  v-for="item in taskTypeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </div>
            <div class="task-item alone" v-if="taskInfoList.taskType === 2">
              <span class="item-label">自</span>
              <el-date-picker
                :class="['item-date', {'red': required && !taskInfoList.startDate}]"
                v-model="taskInfoList.startDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="{disabledDate}"
                @change="changeDate">
              </el-date-picker>
              <el-time-picker
                :class="['item-time', {'red': required && !taskInfoList.startTime}]"
                v-model="taskInfoList.startTime"
                placeholder="选择时间"
                value-format="HH:mm"
                format="HH:mm"
                :picker-options="{
                  selectableRange: selectableRange
                }">
              </el-time-picker>
              <span class="item-label small">每</span>
              <el-input 
                :class="['item-num', {'red': required && !taskInfoList.times}]"
                v-model="taskInfoList.times" 
                placeholder="请输入"
                :onkeyup="taskInfoList.times = JSON.stringify(taskInfoList.times).replace(/[^0-9]/g,'')">
              </el-input>
              <el-select 
                :class="['item-unit', {'red': required && !taskInfoList.timesUnit}]"
                v-model="taskInfoList.timesUnit"
                placeholder="请选择">
                <el-option
                  v-for="item in timesUnitList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
              <span>执行一次</span>
            </div>
            <div class="task-item" v-if="taskInfoList.taskType === 1">
              <span class="item-label">下次执行日期</span>
              <div v-if="isAdd || (!isAdd && isEdit)" class="edit-date">
                <el-date-picker
                  :class="['item-date', {'red': required && !taskInfoList.nextDate}]"
                  v-model="taskInfoList.nextDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="{disabledDate}"
                  @change="changeDate">
                </el-date-picker>
                <el-time-picker
                  :class="['item-time', {'red': required && !taskInfoList.nextTime}]"
                  v-model="taskInfoList.nextTime"
                  placeholder="选择时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  :picker-options="{
                    selectableRange: selectableRange
                  }">
                </el-time-picker>
              </div>
              <div v-else class="edit-date">
                <p>{{ taskInfoList.nextDate }} {{ taskInfoList.nextTime }}</p>
                <span class="edit-text" @click="editDate">编辑</span>
              </div>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="taskTrue">确定</el-button>
            <el-button @click="taskModelShow = false">取消</el-button>
          </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import Empty from '../../components/empty';
  import { TaskResource } from '../../axios/index';
  import { mapActions, mapGetters } from 'vuex';
  import BreadList from '../../components/breadList';
  import { formatDate } from '../../util/util'
  export default {
    name: 'ManageList',
    components: {
      Empty,
      BreadList
    },
    data() {
      return {
        // 表格相关
        listLoading: false,
        tableData: [],
        tablePageData: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          pageSizes: [10, 20, 50],
          inputNum: 1
        },
        // 新增任务/编辑任务弹框
        isAdd: true,
        isEdit: false,
        taskDialogTitle: '新增任务',
        taskModelShow: false,
        taskInfoList: {
          taskName: '',
          modelId: null,
          dataSet: null,
          taskType: 1,
          startDate: '',
          startTime: '',
          times: 1,
          timesUnit: 1,
          nextDate: '',
          nextTime: ''
        },
        selectableRange: '00:00:00 - 23:59:59',
        // 模型列表
        modelList: [],
        modelListProps: {
          children: 'datasetList',
          label: 'name',
          value: 'id'
        },
        // 数据集列表
        dataSetList: [],
        // 任务类型
        taskTypeList: [
          {
            name: '单次任务',
            code: 1
          },
          {
            name: '定时任务',
            code: 2
          },
        ],
        // 周期
        timesUnitList: [
          {
            name: '日',
            code: 1
          },
          {
            name: '月',
            code: 2
          },
          {
            name: '年',
            code: 3
          }
        ],
        // 必填状态
        required: false,
        // 当前选中的任务
        activeTask: null,
        // 面包屑列表
        breadList: [
          {
            modelName: 'ManageList',
            name: '任务管理'
          }
        ]
      }
    },
    mounted() {
      this.getTableList();
    },
    methods: {
      ...mapActions([
        'setActiveItem'
      ]),
      // 规定日期选择范围
      disabledDate(time) {
        return time.getTime() < Date.now() - 8.64e7
      },
      // 任务类型格式化
      taskTypeFormat(row) {
        switch(row.type){
          case 1:
            return '单次任务'
          case 2:
            return '定时任务'
          default:
            return ''
        }
      },
      // 任务状态格式化
      taskStatusFormat(row) {
        switch(row.taskStatus){
          case 1:
            return '运行中'
          case 2:
            return '运行完毕'
          case 3:
            return '运行中止'
          case 4:
            return '执行异常'
          default:
            return ''
        }
      },
      // 获取模型列表
      getModelList(add) {
        TaskResource
        .getModelList()
        .then(res => {
          this.modelList = res.data || [];
          // if(add) {
          //   this.taskInfoList.modelId = this.modelList[0].id;
          // }
          this.modelList.forEach(item => {
            if(item.id === this.taskInfoList.modelId) {
              // 切换对应的数据集
              this.dataSetList = item.datasetList || [];
              // if(add) {
              //   this.taskInfoList.dataSet = this.dataSetList[0].id
              // }
            }
          })
        })
      },
      // 获取数据集列表
      getdataSetList(id) {
        TaskResource
        .getdataSetList({
          modelId: id
        })
        .then(res => {

        })
      },
      // 获取列表数据
      getTableList() {
        let returnTrue = false;
        setTimeout(() => {
          if(!returnTrue) {
            this.listLoading = true;
          }
        }, 100)
        TaskResource
        .queryTaskManageList({
          pageNo: this.tablePageData.currentPage,
          pageSize: this.tablePageData.pageSize
        })
        .then(res => {
          returnTrue = true;
          this.listLoading = false;
          if(res && res.data) {
            this.tablePageData.total = parseInt(res.data.total);
            if(res.data.records) {
              this.tableData = res.data.records;
            }
          }
        })
        .catch(() => {
          returnTrue = true;
          this.listLoading = false;
        })
      },
      // 改变每页size
      handleSizeChange(val) {
        this.tablePageData.pageSize = val;
        this.tablePageData.currentPage = 1;
        this.tablePageData.inputNum = 1;
        this.getTableList()
      },
      // 切页
      handleCurrentChange(val) {
        val = parseInt(val);
        if(!val || val <= 0) {
          val = 1;
        }
        else if(val > Math.ceil(this.tablePageData.total / this.tablePageData.pageSize)) {
          val = Math.ceil(this.tablePageData.total / this.tablePageData.pageSize);
        }
        this.tablePageData.inputNum = val;
        if(val === this.tablePageData.currentPage) {
          return
        }
        this.tablePageData.currentPage = val;
        this.getTableList();
      },
      // 查看任务
      itemLook(item) {
        this.setActiveItem({
          data: true,
          taskId: item.id,
          name: item.taskName
        })
        this.$router.push({path:'/TaskList'})
      },
      // 删除任务
      itemDelete(item) {
        this.$confirm('删除后无法恢复，是否要删除此次任务', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          closeOnPressEscape: false,
          customClass: 'small-tip'
        })
        .then(() => {
          this.listLoading = true;
          TaskResource
          .deleteTask({
            id: item.id
          })
          .then(res => {
            this.$message.success('删除成功');
            this.tablePageData.inputNum = 1;
            this.tablePageData.currentPage = 1;
            this.getTableList();
          })
          .catch(() => {
            this.listLoading = false;
          })
        })
        .catch(() => {

        })
      },
      // 编辑任务
      itemEdit(item) {
        // 获取模型列表
        this.getModelList();
        this.isAdd = false
        this.isEdit = false
        this.taskModelShow = true;
        this.required = false;
        this.taskDialogTitle = '编辑任务';
        this.activeTask = item.id;
        this.taskInfoList = {
          taskName: item.taskName,
          modelId: item.modelId,
          dataSet: item.datasetId,
          taskType: item.type,
          startDate: '',
          startTime: '',
          times: item.frequency,
          timesUnit: item.unit,
          nextDate: '',
          nextTime: ''
        }
        // 单次任务
        if(item.type === 1 && item.taskStartTime) {
          this.taskInfoList.nextDate = item.taskStartTime.split(' ')[0].replace('年', '-').replace('月', '-').replace('日', '');
          this.taskInfoList.nextTime = item.taskStartTime.split(' ')[1];
        }
        // 定时任务
        else if(item.type === 2 && item.taskStartTime) {
          this.taskInfoList.startDate = item.taskStartTime.split(' ')[0].replace('年', '-').replace('月', '-').replace('日', '');
          this.taskInfoList.startTime = item.taskStartTime.split(' ')[1];
        }
      },
      // 编辑日期时间
      editDate() {
        // 单次任务
        if(this.taskInfoList.taskType === 1) {
          this.taskInfoList.nextDate = ''
          this.taskInfoList.nextTime = ''
        }
        // 定时任务
        else if(this.taskInfoList.taskType === 2) {
          this.taskInfoList.startDate = ''
          this.taskInfoList.startTime = ''
        }
        this.isEdit = true
      },
      // 新建任务
      addTask() {
        // 获取模型列表
        this.getModelList(true);
        this.isAdd = true
        this.activeTask = null;
        this.taskModelShow = true;
        this.required = false;
        this.taskDialogTitle = '新建任务';
        this.taskInfoList = {
          taskName: '',
          modelId: null,
          dataSet: null,
          taskType: 1,
          startDate: '',
          startTime: '',
          times: null,
          timesUnit: null,
          nextDate: '',
          nextTime: ''
        }
      },
      // 日期切换
      changeDate(e) {
        this.taskInfoList.nextTime = ''
        this.taskInfoList.startTime = ''
        if (e === formatDate(new Date())) {
          this.selectableRange = `${formatDate(new Date().getTime() + 5 * 60 * 1000, 'hh:MM:ss')} - 23:59:59`
        } else {
          this.selectableRange = '00:00:00 - 23:59:59'
        }
      },
      // 新建/编辑任务确定
      taskTrue() {
        // 必填项判断
        if(!this.taskInfoList.modelId || !this.taskInfoList.dataSet || !this.taskInfoList.taskType || 
           (this.taskInfoList.taskType === 2 && (!this.taskInfoList.times || !this.taskInfoList.timesUnit)) || 
           (!this.taskInfoList.startDate && this.taskInfoList.startTime) || (this.taskInfoList.startDate && !this.taskInfoList.startTime) ||
           (!this.taskInfoList.nextDate && this.taskInfoList.nextTime) || (this.taskInfoList.nextDate && !this.taskInfoList.nextTime)) {
          this.$message.error('请完善任务信息');
          this.required = true;
          return
        }
        let params = {
          taskName: this.taskInfoList.taskName.trim(),
          type: this.taskInfoList.taskType,
          createLoginId: this.userInfo.rybm,
          createLoginName: this.userInfo.mc,
          modelId: this.taskInfoList.modelId,
          modelName: this.modelList.find(item => item.id === this.taskInfoList.modelId) ? this.modelList.find(item => item.id === this.taskInfoList.modelId).name : '',
          datasetId: this.taskInfoList.dataSet,
          datasetName: this.dataSetList.find(item => item.id === this.taskInfoList.dataSet) ? this.dataSetList.find(item => item.id === this.taskInfoList.dataSet).name : '',
        };
        // 点击确定时，如未对时间进行配置，则自动切换未点击确定时的时间
        // 定时任务
        if(this.taskInfoList.taskType === 2) {
          params.taskStartTime = !this.taskInfoList.startDate ? '' : this.taskInfoList.startDate + ' ' + this.taskInfoList.startTime + ':00';
          params.frequency = this.taskInfoList.times;
          params.unit = this.taskInfoList.timesUnit;
        }
        // 单次任务
        else if(this.taskInfoList.taskType === 1) {
          params.taskStartTime = !this.taskInfoList.nextDate ? '' : this.taskInfoList.nextDate + ' ' + this.taskInfoList.nextTime + ':00';
        }
        let taskSave = null;
        if(this.activeTask) {
          params.id = this.activeTask;
          taskSave = TaskResource.updateTask
        }
        else {
          taskSave = TaskResource.addTask;
        }
        taskSave(params)
        .then(res => {
          this.taskModelShow = false;
          if(this.activeTask) {
            this.$message.success('编辑任务成功');
          }
          else {
            this.$message.success('新增任务成功');
          }
          this.tablePageData.currentPage = 1;
          this.getTableList();
        })
      },
      // 模型切换
      modelChange(val) {
        this.modelList.forEach(item => {
          if(item.id === val) {
            // 切换对应的数据集
            this.dataSetList = item.datasetList || [];
            this.taskInfoList.dataSet = this.dataSetList[0].id
          }
        })
      }
    },
    computed: {
      ...mapGetters({
        userInfo: "getUserInfo",
        buttonList: "getButtonPermissions"
      })
    }
  }
</script>

<style scoped lang="scss">
  .all-content {
    width: 100%;
    height: 100%;
  }
  .manage-content {
    width: 100%;
    height: calc(100% - 32px);
    padding: 0 24px;
    background-color: #fff;
    .task-content {
      .task-item {
        width: 50%;
        display: inline-block;
        margin-bottom: 16px;
        .item-label {
          display: inline-block;
          width: 96px;
          padding-right: 12px;
          text-align: right;
        }
        .item-label.small {
          width: 50px;
        }
        .item-value {
          display: inline-block;
          width: calc(100% - 96px);
        }
        .item-date {
          width: 180PX;
          margin-right: 12px;
        }
        .item-time {
          width: 126px;
        }
        .item-num, .item-unit {
          width: 90px;
          margin-right: 12px;
        }
        .edit-date {
          display: inline-block;
          p {
            display: inline-block;
          }
          .edit-text {
            color: #3C86F5;
            text-decoration: underline;
            cursor: pointer;
            display: inline-block;
            margin-left: 12px;
          }
        }
      }
      .task-item.alone {
        width: 100%;
      }
    }
  }
</style>
